﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

using Perseus;
using Perseus.Data;
using Perseus.Plugins;

using Hetymine.Executioner.Data;
using Hetymine.Executioner.Plugins;

namespace Hetymine.Executioner.Controls {
    /// <summary>
    /// Interaction logic for PluginConfigurator.xaml
    /// </summary>
    public partial class PluginConfigurator : UserControl, IConfigurator<IniFile> {
        private IniFile _Config;

        public PluginConfigurator() {
            InitializeComponent();
        }

        #region IConfigurator<IniFile> Members
        public void InitializeConfig(IniFile config) {
            this._Config = config;

            this.cPlugins.Children.Clear();
            foreach (PluginInstance<IPlugin> p in Executioner.PluginService.Plugins) {
                Expander e = new Expander();
                if (this.cPlugins.Children.Count == 0) {
                    e.Margin = new Thickness(0);
                }
                else {
                    e.Margin = new Thickness(0, 10, 0, 0);
                }

                if (!p.Instance.PluginInfo.Name.IsEmpty()) {
                    CheckBox cb = new CheckBox();
                    cb.Content = p.Instance.PluginInfo.Name;
                    cb.IsChecked = this._Config.GetBool(p.Instance.PluginInfo.Name, "Enabled", true);
                    this.UpdateEnabledToolTip(cb);
                    cb.Click += new RoutedEventHandler(Enable_Click);
                    e.Header = cb;
                }
                else {
                    e.Header = "<unknown>";
                }
                e.Expanded += new RoutedEventHandler(Expanded);

                PluginInfo pi = new PluginInfo(p.Instance.PluginInfo);

                e.Content = pi;

                this.cPlugins.Children.Add(e);
            }
        }

        private void Enable_Click(object sender, RoutedEventArgs e) {
            CheckBox checkBox = sender as CheckBox;
            string name = checkBox.Content.ToString();

            this.UpdateEnabledToolTip(checkBox);

            this._Config.SetBool(name, "Enabled", checkBox.IsChecked.Value);
        }
        private void UpdateEnabledToolTip(CheckBox checkBox) {
            if (checkBox.IsChecked.Value) {
                checkBox.ToolTip = "Plugin is enabled";
            }
            else {
                checkBox.ToolTip = "Plugin is disabled";
            }
        }

        private void Expanded(object sender, RoutedEventArgs e) {
            foreach (Expander expander in this.cPlugins.Children) {
                if (!expander.Equals(sender)) {
                    expander.IsExpanded = false;
                }
            }
        }
        public UserControl ConfigPanel { get { return this; } }
        #endregion
    }
}
